package com.skivingcloud.admin.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 免密登录Token提供者,需要在security配置类中设置该提供者，实现免密登录
 * @author hushouquan
 */
@Component
public class NoPasswordTokenProvider implements AuthenticationProvider{
    private final MyUserDetailsServiceImpl userDetailsService;

    public NoPasswordTokenProvider(MyUserDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException{
        NoPasswordToken noPasswordToken = (NoPasswordToken) authentication;
        String loginName = (String) noPasswordToken.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginName);
        return new NoPasswordToken(userDetails, userDetails.getAuthorities());
    }
    
    @Override
    public boolean supports(Class<?> authentication){
        return NoPasswordToken.class.isAssignableFrom(authentication);
    }
}
